package com.zhz.lib.cms.manage.hotlink;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.hibernate.Hibernate;
import org.hibernate.classic.Session;

import com.zhz.project.common.util.hibernate.BaseDAO;
import com.zhz.lib.cms.domain.hotlink.hotlink;
import com.zhz.project.common.util.zhzutil.ZhzHttpRequestUtil;
import com.zhz.project.common.util.zhzutil.ZhzStringUtil;
import com.zhz.project.common.util.alibaba.StringUtil;

public class hotlinkAction extends DispatchAction {
	private BaseDAO baseDao;
	private Integer pageSize;

	/**
	 * 不给参数，默认执行此处
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * @see org.apache.struts.actions.DispatchAction#unspecified(org.apache.struts.action.ActionMapping,
	 *      org.apache.struts.action.ActionForm,
	 *      javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 */
	public ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		return hotlinklist(mapping, form, request, response);
	}

	/**
	 * 显示链接列表！！
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public ActionForward hotlinklist(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 取出选择的链接类型
		String radiooption = ZhzHttpRequestUtil.getParameters(request,
				"radiooption");
		// 获取搜索框的类型
		String keywordType = ZhzHttpRequestUtil.getParameters(request,
				"keywordType");
		// 获取搜索框的值
		String keyword = ZhzHttpRequestUtil.getParameters(request, "keyword");
		String keywordOut = null;
		if (StringUtil.isNotBlank(keyword)) {
			keyword = URLDecoder.decode(keyword);
			keywordOut = URLEncoder.encode(URLEncoder.encode(keyword));
		}

		// ///////////////////////////////////////
		// 获取页值
		int pageNow = 0;
		String pageNowString = ZhzHttpRequestUtil.getParameters(request,
				"pageNow");

		if (ZhzStringUtil.isNotNull(pageNowString)) {
			pageNow = Integer.parseInt(pageNowString.trim());
		} else {
			pageNow = 1;
		}
		if (pageNow <= 1)
			pageNow = 1;
		// ///////////////////////////////////////

		// ///////////////////////////////////////
		// 构造查询条件，获得查询结果的数量
		int entryTatal = 0;
		String whereStatement = null;

		if (StringUtil.equalsIgnoreCase(keywordType, "title")
				|| StringUtil.equalsIgnoreCase(keywordType, "url")) {
			entryTatal = baseDao.getNumOnQuery(" FROM hotlink where   "
					+ keywordType + " like '%" + keyword + "%'");
			whereStatement = "where  " + keywordType + " like '%" + keyword
					+ "%'";
		} else {
			entryTatal = baseDao.getNumOnQuery(" FROM hotlink ");
			whereStatement = "";
		}
		if (!StringUtil.equals("all", radiooption)) {
			if (StringUtil.isNotBlank(radiooption)) {
				// 根据选择的链接类型选项进行查询
				entryTatal = baseDao
						.getNumOnQuery(" FROM hotlink where   type='"
								+ radiooption + "'");
				whereStatement = "where   type=" + "'" + radiooption + "'";
			}
		}
		int pageTatal = 0;
		if (entryTatal / pageSize == 0)
			pageTatal = entryTatal / pageSize;
		else
			pageTatal = entryTatal / pageSize + 1;
		if (pageNow > pageTatal) {
			pageNow = pageTatal;
		}

		List<hotlink> hotlinklist = baseDao.findAllByPage("hotlink",
				whereStatement, "order by type DESC", pageNow, pageSize);
		// 查询的结果集
		request.setAttribute("hotlinklist", hotlinklist);

		request.setAttribute("pageNow", pageNow);
		request.setAttribute("pageSize", pageSize);
		request.setAttribute("pageTatal", pageTatal);
		request.setAttribute("entryTatal", entryTatal);
		request.setAttribute("keyword", keywordOut);
		request.setAttribute("keywordType", keywordType);
		request.setAttribute("radiooption", radiooption);

		return mapping.findForward("hotlink-list");
	}

	/**
	 * 添加链接！！
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward hotlinkadd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		return mapping.findForward("hotlink-add");
	}

	/**
	 * 保存新添加的链接！！
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward hotlinksave(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		String title = ZhzHttpRequestUtil.getParameters(request, "title");
        String url = ZhzHttpRequestUtil.getParameters(request, "url");
        String urltwo = ZhzHttpRequestUtil.getParameters(request, "urltwo");
		String type = ZhzHttpRequestUtil.getParameters(request, "type");
        // 获取排序
        String sortNumber = ZhzHttpRequestUtil.getParameters(request, "sortNumber");

		hotlink hotlink = new hotlink();

		hotlink.setTitle(title);
		hotlink.setUrl(url);
		hotlink.setUrltwo(urltwo);
		hotlink.setType(type);
        if (StringUtil.isNotBlank(sortNumber) && StringUtil.isNumeric(sortNumber)) {
            hotlink.setSortNumber(Integer.valueOf(sortNumber));
        } else {
            hotlink.setSortNumber(getMaxSortNumber(type));
        }
		boolean save = baseDao.save(hotlink);

		if (save) {
			request.setAttribute("addresult", "addresult");
			request.setAttribute("add", "add");
		}

		/**
		 * 返回
		 */
		return mapping.findForward("hotlink-result");

	}

	/**
	 * 编辑链接
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward hotlinkedit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		String hotlinkid = ZhzHttpRequestUtil.getParameters(request,
				"hotlinkid");

		if (ZhzStringUtil.isNotNull(hotlinkid)) {
			hotlink hotlink = (hotlink) baseDao.findOneObject("hotlink", "id",
					hotlinkid);
			request.setAttribute("hotlink", hotlink);
		}

		return mapping.findForward("hotlinkedit-form");
	}

	/**
	 * 保存编辑后的链接
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	public ActionForward hotlinkeditsave(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {

		String hotlinkid = ZhzHttpRequestUtil.getParameters(request,
				"hotlinkid");
		String title = ZhzHttpRequestUtil.getParameters(request, "title");
		String url = ZhzHttpRequestUtil.getParameters(request, "url");
        String urltwo = ZhzHttpRequestUtil.getParameters(request, "urltwo");
		String type = ZhzHttpRequestUtil.getParameters(request, "type");
        // 获取排序
        String sortNumber = ZhzHttpRequestUtil.getParameters(request, "sortNumber");

		if (ZhzStringUtil.isNotNull(hotlinkid)) {
			hotlink hotlink = (hotlink) baseDao.findOneObject("hotlink", "id",
					hotlinkid);

			hotlink.setTitle(title);
			hotlink.setUrl(url);
			hotlink.setUrltwo(urltwo);
			hotlink.setType(type);
            if (StringUtil.isNotBlank(sortNumber) && StringUtil.isNumeric(sortNumber)) {
                hotlink.setSortNumber(Integer.valueOf(sortNumber));
            } else {
                hotlink.setSortNumber(getMaxSortNumber(type));
            }
			boolean update = baseDao.update(hotlink);

			if (update) {
				request.setAttribute("editresult", "editresult");
				request.setAttribute("edit", "edit");
			}
		}
		return mapping.findForward("hotlink-result");
	}

	/**
	 * 删除链接
	 */
	public ActionForward hotlinkdel(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String hotlinkid = ZhzHttpRequestUtil.getParameters(request,
				"hotlinkid");

		if (ZhzStringUtil.isNotNull(hotlinkid)) {
			boolean delResult = baseDao.execute("delete from hotlink where id="
					+ hotlinkid);
			if (delResult) {
				request.setAttribute("del", "del");
				request.setAttribute("delResult", "delResult");
			}
		}
		/**
		 * 返回
		 */
		return mapping.findForward("hotlink-result");
	}
    private Integer getMaxSortNumber(String type) {
        String sql = "select max(sortNumber) sortNumber from hotlink where type='" + type + "'";
        Session session = baseDao.getHibernateTemplate().getSessionFactory().openSession();
        Integer maxId = (Integer) (session.createSQLQuery(sql).addScalar("sortNumber",
            Hibernate.INTEGER)).uniqueResult();
        // 比最大值步进10
        if (maxId != null) {
            return maxId + 10;
        } else {
            return 10;
        }
    }

	public void setBaseDao(BaseDAO baseDao) {
		this.baseDao = baseDao;
	}

	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}

}
